﻿using System.Collections;
using System.Html;
using System.Runtime.CompilerServices;
using jQueryApi;
using System;

namespace StorytellingScript
{
    [GlobalMethods]
    public static class Chat
    {
        public static void ConfigurarChat()
        {
            jQuery.Select("#chatResizable").Plugin<StorytellingPlugin>().Resizable(new Dictionary(
                "containment", "parent"
                ));

            Global.Autocompletar("Acao");

            AutocompleteAcoes("/Personagem/MeusPersonagens", "meuPersonagem", delegate(Dictionary dictionary) { });

            AutocompleteAcoes("/Personagem/MeusEquipamentos", "meuEquipamento",
                delegate(Dictionary dictionary) {
                    dictionary["id"] = jQuery.Select("#meuPersonagemAutocomplete_0").GetValue();
                });
        }

        public static void AutocompleteAcoes(string url, string inputId, Action<Dictionary> action)
        {
            Dictionary dictionary = new Dictionary();
            jQueryObject inputText = jQuery.Select(string.Format("#{0}", inputId));
            jQueryObject inputHidden = jQuery.Select(string.Format("#{0}Autocomplete_0", inputId));
            inputText.Plugin<StorytellingPlugin>().Autocomplete(new Dictionary(
                 "source", new Action<object, Action<object>>(delegate(object request, Action<object> response)
                 {
                     dictionary["nome"] = Script.Literal("{0}.term", request);

                     action(dictionary);

                     jQueryAjaxOptions options = new jQueryAjaxOptions();
                     options.Url = url;
                     options.Type = "POST";
                     options.DataType = "json";
                     options.Data = dictionary;
                     options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
                     {
                         response(jQuery.Map(data, new ObjectMapCallback(delegate(object item, string key)
                         {
                             return new Dictionary("label", Script.Literal("{0}.Nome", item), "value", Script.Literal("{0}.Id", item));
                         })));
                     });

                     jQuery.Ajax(options);
                 }),
                 "focus", new Func<jQueryEvent, object, bool>(delegate(jQueryEvent e, object ui)
                 {
                     inputText.Value(Script.Literal("{0}.item.label", ui).ToString());
                     return false;
                 }),
                 "select", new Func<jQueryEvent, object, bool>(delegate(jQueryEvent e, object ui)
                 {
                     inputHidden.Value(Script.Literal("{0}.item.value", ui).ToString());
                     return false;
                 })
                 ));

            inputText.Bind("focus", new jQueryEventHandler(delegate(jQueryEvent e)
            {
                if (inputHidden.Length > 0 && inputHidden.GetValue() != "0")
                {
                    inputText.Value("");
                    inputHidden.Value("0");
                }
            }));
        }

        public static void CarregarChat()
        {
            CarregarChatUrl("/Home/Chat");
        }

        public static void CarregarChatUrl(string url)
        {
            jQueryAjaxOptions options = new jQueryAjaxOptions();
            options.Url = url;
            options.Type = "POST";
            options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
            {
                jQueryObject chat = jQuery.Select("#chat");

                jQuery.Each(data, new ObjectIterationCallback(delegate(string name, object value)
                {
                    int tipo = (int) Script.Literal("{0}.Tipo", value);
                    if (tipo == 1)
                    {
                        chat.Html(string.Format(Template.ChatJogada,
                        Script.Literal("{0}.NomeUsuario", value),
                        Script.Literal("{0}.Ocorrido", value),
                        Script.Literal("{0}.Sucessos", value),
                        Script.Literal("{0}.Dados", value),
                        Script.Literal("{0}.Explosao", value),
                        Script.Boolean(Script.Literal("{0}.Anulador", value)) ? "Sim" : "Não",
                        Script.Literal("{0}.Resultado", value),
                        chat.GetHtml()));
                    }
                    else if (tipo == 0)
                    {
                        object sinal = Script.Literal("{0}.SinalModificador", value);

                        chat.Html(string.Format(Template.ChatAcao,
                        Script.Literal("{0}.NomeUsuario", value),
                        Script.Literal("{0}.Ocorrido", value),
                        Script.Literal("{0}.Personagem", value),
                        Script.Literal("{0}.Acao", value),
                        Script.Literal("{0}.Equipamento", value),
                        !Script.IsNullOrUndefined(sinal) ? (Script.Boolean(sinal) ? "+" : "-") : "",
                        Script.Literal("{0}.Modificador", value),
                        Script.Literal("{0}.Sucessos", value),
                        Script.Literal("{0}.Dados", value),
                        Script.Literal("{0}.Explosao", value),
                        Script.Boolean(Script.Literal("{0}.Anulador", value)) ? "Sim" : "Não",
                        Script.Literal("{0}.Resultado", value),
                        chat.GetHtml()));
                    }
                    else
                    {
                        StringBuilder jogadoresBuilder = new StringBuilder();

                        jQuery.Each(Script.Literal("{0}.Colecao", value),
                            new ObjectIterationCallback(delegate(string nameJogador, object valueJogador)
                        {
                            StringBuilder itemBuilder = new StringBuilder();

                            jQuery.Each(Script.Literal("{0}.Value", valueJogador),
                                new ObjectIterationCallback(delegate(string nameItem, object valueItem)
                            {
                                itemBuilder.Append(string.Format(Template.ChatColecaoItem, valueItem));
                            }));

                            jogadoresBuilder.Append(string.Format(Template.ChatColecao,
                                Script.Literal("{0}.Key", valueJogador),
                                itemBuilder
                                ));
                        }));

                        chat.Html(string.Format(Template.ChatStatus,
                        Script.Literal("{0}.NomeUsuario", value),
                        Script.Literal("{0}.Ocorrido", value),
                        jogadoresBuilder,
                        chat.GetHtml()));
                    }
                }));

                Window.SetTimeout(CarregarChat, 3000);
            });

            jQuery.Ajax(options);
        }

        public static void InicioEnvioChat()
        {
            jQuery.Select("#chatTabs").Plugin<StorytellingPlugin>().Block(new Dictionary("message", "<h1>Aguarde</h1>"));
            jQuery.Select(".InputResetar").Value("0");
            EsconderChat();
        }

        public static void FimEnvioChat()
        {
            jQuery.Select("#chatTabs").Plugin<StorytellingPlugin>().Unblock();
            AparecerChat();
        }

        public static void AparecerChat()
        {
            jQuery.Select("#chat").FadeIn();
        }

        public static void EsconderChat()
        {
            jQuery.Select("#chat").FadeOut();
        }

        public static void BloquearTabGerenciarStatus()
        {
            jQuery.Select("#chatTabs").Plugin<StorytellingPlugin>().Tabs("disable", 2);
        }

        public static void ConfigurarGerenciarStatus()
        {
            jQuery.Select("#autoCronica").Plugin<StorytellingPlugin>().Autocomplete(new Dictionary(
                "source", new Action<object, Action<object>>(delegate(object request, Action<object> response)
                {
                    jQueryAjaxOptions options = new jQueryAjaxOptions();
                    options.Url = "/Cronica/CronicasPessoal";
                    options.Type = "POST";
                    options.DataType = "json";
                    options.Data = new Dictionary("nome", Script.Literal("{0}.term", request));
                    options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
                    {
                        response(jQuery.Map(data, new ObjectMapCallback(delegate(object item, string key)
                        {
                            return new Dictionary("label", Script.Literal("{0}.Nome", item), "value", Script.Literal("{0}.Id", item));
                        })));
                    });

                    jQuery.Ajax(options);
                }),
                "focus", new Func<jQueryEvent, object, bool>(delegate(jQueryEvent e, object ui)
                {
                    jQuery.Select("#autoCronica").Value(Script.Literal("{0}.item.label", ui).ToString());
                    return false;
                }),
                "select", new Func<jQueryEvent, object, bool>(delegate(jQueryEvent e, object ui)
                {
                    jQueryAjaxOptions options = new jQueryAjaxOptions();
                    options.Url = "/Personagem/CronicaPersonagens";
                    options.Type = "POST";
                    options.DataType = "json";
                    options.Data = new Dictionary("id", Script.Literal("{0}.item.value", ui));
                    options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
                    {
                        jQueryObject tbody = jQuery.Select("#personagens tbody");

                        tbody.Html("");

                        jQuery.Each(data, new ObjectIterationCallback(delegate(string indice, object value)
                        {    
                            tbody.Append(string.Format(Template.Status, Script.Literal("{0}.Nome", value), indice, Script.Literal("{0}.Id", value)));
                        }));

                        Global.AplicarPadrao();
                    });

                    jQuery.Ajax(options);
                    return false;
                })
                ));
        }
    }
}
